
#include "timer.h"

void timer_init(int timer, int mode) {
	outportb(TIMER_CTRL, ((0x03 & timer) << 6) | mode);
}

void timer_load(int timer, int value) {
	timer_init(timer, LCOM_MODE);
	outportb(timer, LSB(value));
	outportb(timer, MSB(value));
}

void mili_sleep(int mili) {
	timer_load(TIMER_0, TIMER_CLK / 1000);
	
	void t0_isr(void); ///< t0 isr handler to count mili and sec
	extern int time_tick; ///< Used in t0_isr, counts miliseconds
	extern int sec_tick; ///< Used in t0_isr, counts seconds

	_go32_dpmi_seginfo old_irq;
	install_asm_irq_handler(T0_IRQ, t0_isr, &old_irq);
	
	int end = sec_tick * 1000 + time_tick + mili;
	
	while (sec_tick * 1000 + time_tick < end) {}
	
	reinstall_asm_irq_handler(T0_IRQ, &old_irq);
}

void sec_sleep(int secs) {
	timer_load(TIMER_0, TIMER_CLK / 1000);

	void t0_isr(void); ///< t0 isr handler to count mili and sec
	extern int sec_tick; ///< Used in t0_isr, counts seconds

	_go32_dpmi_seginfo old_irq;
	install_asm_irq_handler(T0_IRQ, t0_isr, &old_irq);
	
	int end = sec_tick + secs;
	
	while (sec_tick < end) {}
	
	reinstall_asm_irq_handler(T0_IRQ, &old_irq);
}

int get_divider(float freq) {

	if(!freq) return -1;
	return (int)(TIMER_CLK/freq+0.5);

}
